package btc

import (
	"encoding/hex"
	"errors"
	"fmt"
	"os/exec"
	"strings"

	"gitee.com/coin-kit/base43"

	"github.com/astaxie/beego"
	"github.com/tidwall/gjson"
)

type Command struct {
	Testnet  uint64
	Cmd      string
	Electrum string
	Datadir  string
}

var CommandGlobal *Command

func (c *Command) DaemonStop() error {
	params := []string{}
	//params = append(params, c.Electrum)
	if c.Testnet == 1 {
		params = append(params, "--testnet")
	}

	params = append(params, "daemon")
	params = append(params, "stop")
	params = append(params, "-D")
	params = append(params, c.Datadir)
	beego.Debug(c.Cmd, params)
	resp := exec.Command(c.Cmd, params...)
	raw, _ := resp.Output()
	beego.Debug(string(raw))
	if string(raw) == "Daemon not running\n" || string(raw) == "Daemon stopped\n" {
		return nil
	}

	return errors.New("Unkown Electrum Stop Error")
}

func (c *Command) DaemonStart() error {
	params := []string{}
	//params = append(params, c.Electrum)
	if c.Testnet == 1 {
		params = append(params, "--testnet")
	}

	params = append(params, "daemon")
	params = append(params, "start")
	params = append(params, "-D")
	params = append(params, c.Datadir)
	resp := exec.Command(c.Cmd, params...)

	beego.Debug(c.Cmd, params)
	err := resp.Run()

	if err != nil {
		return err
	}
	return nil
}

func (c *Command) DaemonLoad() error {
	params := []string{}
	//params = append(params, c.Electrum)
	if c.Testnet == 1 {
		params = append(params, "--testnet")
	}

	params = append(params, "daemon")
	params = append(params, "load_wallet")
	params = append(params, "-D")
	params = append(params, c.Datadir)
	beego.Debug(c.Cmd, params)
	resp := exec.Command(c.Cmd, params...)
	raw, _ := resp.Output()
	beego.Debug(string(raw))
	err := resp.Run()
	if err != nil {
		return err
	}
	return nil
}

//func (c *Command) PayTo(from string, to string, amount, fee float64) (string, error) {
//	params := []string{}
//	//params = append(params, c.Electrum)
//	if c.Testnet == 1 {
//		params = append(params, "--testnet")
//	}
//	params = append(params, "payto")
//	params = append(params, to)
//	params = append(params, fmt.Sprintf("%.8f", float64(amount)))
//	params = append(params, "-f")
//	params = append(params, fmt.Sprintf("%.8f", fee))
//	params = append(params, "-F")
//	params = append(params, from)
//	params = append(params, "-c")
//	params = append(params, from)

//	params = append(params, "-D")
//	params = append(params, c.Datadir)
//	beego.Debug(c.Cmd, params)
//	resp := exec.Command(c.Cmd, params...)
//	raw, err := resp.CombinedOutput()
//	str := string(raw)

//	str11 := `/usr/local/lib/python3.7/site-packages/google/protobuf/descriptor.py:47: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working \
//  from google.protobuf.pyext import _message \
///usr/local/lib/python3.7/site-packages/google/protobuf/internal/well_known_types.py:788: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working \
//  collections.MutableMapping.register(Struct)`
//	str = strings.Replace(str, str11, "", -1)
//	str = strings.Replace(str, "\n", "", -1)

//	fmt.Println(string(raw), err)
//	if err != nil {
//		if strings.Contains(string(raw), "NotEnoughFunds") == true {
//			return "", errors.New("余额不足command payto call error not enough funds")
//		}
//		return "", errors.New("command payto call error " + string(raw))
//	}
//	obj := gjson.ParseBytes([]byte(str))
//	hex0 := obj.Get("hex").String()
//	data, err := hex.DecodeString(hex0)
//	if err != nil {
//		return "", errors.New("编码出错" + err.Error())
//	}
//	str1 := base43.Encode(data)
//	return str1, nil
//}

//func (c *Command) Broadcast(rawtx string) (string, error) {

//	str2, err := base43.Decode(rawtx)
//	if err != nil {
//		return "", errors.New("解码出错" + err.Error())
//	}
//	rawtxhex := hex.EncodeToString(str2)

//	params := []string{}
//	//params = append(params, c.Electrum)
//	if c.Testnet == 1 {
//		params = append(params, "--testnet")
//	}
//	params = append(params, "broadcast")
//	params = append(params, rawtxhex)
//	params = append(params, "-D")
//	params = append(params, c.Datadir)
//	beego.Debug(c.Cmd, params)
//	resp := exec.Command(c.Cmd, params...)
//	raw, err := resp.Output()
//	str := string(raw)
//	beego.Debug(str)
//	str11 := `/usr/local/lib/python3.7/site-packages/google/protobuf/descriptor.py:47: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working \
//  from google.protobuf.pyext import _message \
///usr/local/lib/python3.7/site-packages/google/protobuf/internal/well_known_types.py:788: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working \
//  collections.MutableMapping.register(Struct)`
//	str = strings.Replace(str, str11, "", -1)
//	str = strings.Replace(str, "\n", "", -1)

//	if err != nil {
//		return "", errors.New("command broadcast call error:" + string(raw))
//	}

//	if len(str) == 64 {
//		return str, nil
//	}

//	obj := gjson.ParseBytes([]byte(str))
//	if len(obj.Array()) != 2 {
//		return "", errors.New("command broadcast return value error:" + string(raw))
//	}
//	if obj.Array()[0].Bool() == false {
//		msg := obj.Array()[1].String()
//		if strings.Contains(msg, "dust") == true {
//			return "", errors.New("command broadcast error dust transaction")
//		}
//		return "", errors.New("command broadcast" + msg)
//	}
//	txhash := obj.Array()[1].String()
//	return txhash, nil
//}

//func (c *Command) Getaddressbalance(add string) float64 {

//	params := []string{}
//	//params = append(params, c.Electrum)
//	if c.Testnet == 1 {
//		params = append(params, "--testnet")
//	}
//	params = append(params, "getaddressbalance")
//	params = append(params, add)
//	params = append(params, "-D")
//	params = append(params, c.Datadir)
//	beego.Debug(c.Cmd, params)
//	resp := exec.Command(c.Cmd, params...)
//	raw, err := resp.CombinedOutput()
//	if err != nil {
//		return 0
//	}
//	str := string(raw)
//	beego.Debug(str)
//	str11 := `/usr/local/lib/python3.7/site-packages/google/protobuf/descriptor.py:47: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working \
//  from google.protobuf.pyext import _message \
///usr/local/lib/python3.7/site-packages/google/protobuf/internal/well_known_types.py:788: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working \
//  collections.MutableMapping.register(Struct)`
//	str = strings.Replace(str, str11, "", -1)
//	str = strings.Replace(str, "\n", "", -1)

//	obj := gjson.ParseBytes([]byte(str))

//	balancestr := obj.Get("confirmed").String()
//	v2, _ := strconv.ParseFloat(balancestr, 64)
//	return v2
//}

func (c *Command) PayToUsdt(from string, to1, to2 string, fee float64) (string, error) {
	params := []string{}
	//params = append(params, c.Electrum)
	if c.Testnet == 1 {
		params = append(params, "--testnet")
	}
	params = append(params, "paytousdt")
	params = append(params, to1)
	params = append(params, fmt.Sprintf("%.8f", float64(0)))
	params = append(params, to2)
	params = append(params, fmt.Sprintf("%.8f", float64(0.00000546)))
	params = append(params, "-f")
	params = append(params, fmt.Sprintf("%.8f", fee))
	params = append(params, "-F")
	params = append(params, from)
	params = append(params, "-c")
	params = append(params, from)

	params = append(params, "-D")
	params = append(params, c.Datadir)
	beego.Debug(c.Cmd, params)
	resp := exec.Command(c.Cmd, params...)
	raw, err := resp.CombinedOutput()
	str := string(raw)
	beego.Debug(str)
	str11 := `/usr/local/lib/python3.7/site-packages/google/protobuf/descriptor.py:47: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working \
  from google.protobuf.pyext import _message \
/usr/local/lib/python3.7/site-packages/google/protobuf/internal/well_known_types.py:788: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working \
  collections.MutableMapping.register(Struct)`
	str = strings.Replace(str, str11, "", -1)
	str = strings.Replace(str, "\n", "", -1)

	fmt.Println(string(raw), err)
	if err != nil {
		if strings.Contains(string(raw), "NotEnoughFunds") == true {
			return "", errors.New("余额不足command payto call error not enough funds")
		}
		return "", errors.New("command payto call error " + string(raw))
	}
	obj := gjson.ParseBytes([]byte(str))
	hex0 := obj.Get("hex").String()
	data, err := hex.DecodeString(hex0)
	if err != nil {
		return "", errors.New("编码出错" + err.Error())
	}
	str1 := base43.Encode(data)
	return str1, nil
}
